package org.fhawk.tinyspring.tx;

import org.fhawk.tinyspring.aop.proxy.Proxy;
import org.fhawk.tinyspring.exception.ProxyException;
import org.fhawk.tinyspring.orm.ConnectionFactory;

import java.lang.reflect.Method;
import java.sql.SQLException;

/**
 * Created by tuo on 10/9/16.
 */
public class TransactionProxy implements Proxy {
    private ThreadLocal<Boolean> check = ThreadLocal.withInitial(() -> false);

    @Override
    public void doBefore(Method method) throws ProxyException {
        if (!check.get()) {
            check.set(true);
            try {
                ConnectionFactory.beginTransaction();
            } catch (SQLException e) {
                throw new ProxyException(e);
            }
        }

    }

    @Override
    public void doAfter(Method method) throws ProxyException {
        if (check.get()) {
            try {
                ConnectionFactory.commit();
            } catch (SQLException e) {
                throw new ProxyException(e);
            }
        }
    }

    @Override
    public void doFinally(Method method) {
        check.remove();
    }

    @Override
    public void doThrowable(Method method, Throwable e) throws ProxyException {
        if (check.get()) {
            try {
                ConnectionFactory.rollback();
            } catch (SQLException e1) {
                throw new ProxyException(e);
            }
        }
    }
}
